let monitoredSites = {};
let previousTabId = null;

chrome.runtime.onInstalled.addListener(() => {
    loadMonitoredSites();
});

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.action === 'updateMonitoredSites') {
        loadMonitoredSites();
    }
});

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
    if (changeInfo.status === 'complete') {
        const url = new URL(tab.url);
        const hostname = url.hostname;
        console.info("标签变化 to " + hostname);

        if (monitoredSites[hostname] != null && tabId !== previousTabId) {
            chrome.tabs.sendMessage(tabId, { action: "showAlert", message: monitoredSites[hostname] });
            previousTabId = tabId;
        } else {
            console.log("不是监控网站或者是同一个标签页");
        }
    }
});

async function loadMonitoredSites() {
    chrome.storage.local.get(['monitoredSites'], (result) => {
        if (result.monitoredSites) {
            monitoredSites = result.monitoredSites;
            console.log('Updated monitoredSites in background:', monitoredSites);
        } else {
            console.log('No monitored sites found in storage.');
        }
    });
}

function saveMonitoredSites() {
    chrome.storage.local.set({ monitoredSites: monitoredSites }, () => {
        console.log('Saved monitoredSites:', monitoredSites);
    });
}

chrome.runtime.onSuspend.addListener(() => {
    saveMonitoredSites();
});
